package java.Servlet;

import Service.CaptchaStoreService;
import Service.UserService;
import entity.User;
import exception.AuthException;
import org.json.JSONException;
import org.json.JSONObject;
import utils.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Author Su
 * @Date 2025/4/17 16:16
 * @Version 1.0 （版本号）
 */
@WebServlet("/api/auth/login")
public class LoginServlet extends HttpServlet {
    private UserService userService;

    @Override
    public void init() throws ServletException {
        try {
            Connection connection = DBUtil.getConnection();
            this.userService = new UserService(connection);
        } catch (SQLException e) {
            throw new ServletException("初始化数据库连接失败", e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        JSONObject responseJson = new JSONObject();

        try {
            // 1. 解析请求体
            BufferedReader reader = req.getReader();
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

            JSONObject requestJson = new JSONObject(sb.toString());
            String username = requestJson.getString("username");
            String password = requestJson.getString("password");
            String captcha = requestJson.getString("captcha");

            // 2. 验证验证码
            HttpSession session = req.getSession(false);
            if (session == null || !CaptchaStoreService.validateCaptcha(session.getId(), captcha)) {
                responseJson.put("code", 400);
                responseJson.put("message", "验证码错误或已过期");
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }

            // 3. 验证登录
            User user = userService.login(username, password);

            // 4. 创建会话
            session = req.getSession();
            session.setAttribute("user", user);
            session.setMaxInactiveInterval(30 * 60); // 30分钟超时

            // 5. 返回成功响应
            responseJson.put("code", 200);
            responseJson.put("message", "登录成功");
            responseJson.put("data", new JSONObject()
                    .put("userId", user.getUserId())
                    .put("username", user.getUsername())
                    .put("email", user.getEmail())
            );

            resp.setStatus(HttpServletResponse.SC_OK);
        } catch (JSONException e) {
            responseJson.put("code", 400);
            responseJson.put("message", "请求参数错误");
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } catch (AuthException e) {
            responseJson.put("code", 401);
            responseJson.put("message", e.getMessage());
            resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        } catch (Exception e) {
            responseJson.put("code", 500);
            responseJson.put("message", "系统错误");
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            e.printStackTrace();
        } finally {
            try (PrintWriter out = resp.getWriter()) {
                out.print(responseJson.toString());
            }
        }
    }
}